package jdbc;

import java.sql.*;
import java.util.Date;

/**
 * 测试PreparedStatement
 */
public class Demo03 {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            //加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc?serverTimezone=Asia/Shanghai","root","123456");

            String sql="insert into t_user (username,pwd,regTime) value (?,?,?)";//?是占位符
            ps=conn.prepareStatement(sql);
            //ps.setString(1,"邓俊杰");//1,代表你要传参的位置
            //ps.setString(2,"54321");
            //ps.setTimestamp(3, new Timestamp(new Date().getTime()));
            //可以使用setObject方法处理参数,无需考虑类型
            ps.setObject(1,"钟宏伟");
            ps.setObject(2,"5124");
            ps.setObject(3,new Timestamp(new Date().getTime()));
            //ps.execute();//返回是否有结果集,是Boolean类型
            int count=ps.executeUpdate();//返回的是数值,记录有多少条数据更改
            System.out.println(count);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
